import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:dio/native_imp.dart';
import 'package:flutter/foundation.dart';

import 'interceptors/logger.dart';
import 'interceptors/request_before.dart';
import 'interceptors/response_after.dart';

/// 网络请求
class HttpClientDio extends DioForNative {
  /// 工厂模式
  factory HttpClientDio() => _getInstance();

  /// 单利
  static HttpClientDio get instance => _getInstance();
  static HttpClientDio? _instance;

  HttpClientDio._internal() {
    /// 通用处理
    (transformer as DefaultTransformer).jsonDecodeCallback = _parseJson;
    options = BaseOptions(connectTimeout: 5000, receiveTimeout: 30000, sendTimeout: 30000);
    interceptors.addAll([
      RequestBeforeInterceptors(),
      LoggerInterceptors(),
      ResponseAfterInterceptors(),
    ]);
  }

  static HttpClientDio _getInstance() {
    _instance ??= HttpClientDio._internal();
    return _instance!;
  }
}

/// 解析json
_parseJson(String text) => compute(_parseAndDecode, text);

_parseAndDecode(String response) => jsonDecode(response);
